#include "stdafx.h"
#include "net/HTTPStreamFactory.hpp"
#include "net/HTTPClientSession.hpp"
#include "net/HTTPRequest.hpp"
#include "net/HTTPResponse.hpp"
#include "net/HTTPResponseStream.hpp"
#include "net/HTTPCredentials.hpp"
#include "net/URIStreamOpener.hpp"
#include "stream/StreamCopier.hpp"
using JHCPP::stream::CStreamCopier;

NET_NAMESPACE_BEGIN

CHTTPStreamFactory::CHTTPStreamFactory() : m_proxyPort(CHTTPSession::HTTP_PORT)
{
}

CHTTPStreamFactory::CHTTPStreamFactory(const std::string& proxyHost, UInt16 proxyPort)
	: m_proxyHost(proxyHost), m_proxyPort(proxyPort)
{
}

CHTTPStreamFactory::CHTTPStreamFactory(const std::string& proxyHost, UInt16 proxyPort, const std::string& proxyUsername, const std::string& proxyPassword)
	: m_proxyHost(proxyHost),
	m_proxyPort(proxyPort),
	m_proxyUsername(proxyUsername),
	m_proxyPassword(proxyPassword)
{
}

CHTTPStreamFactory::~CHTTPStreamFactory()
{
}

std::istream* CHTTPStreamFactory::open(const CURI& uri)
{
	jh_assert (uri.getScheme() == "http");

	CURI resolvedURI(uri);
	CURI proxyUri;
	CHTTPClientSession* pSession = 0;
	CHTTPResponse res;
	bool retry = false;
	bool authorize = false;
	std::string username;
	std::string password;

	try
	{
		do
		{
			if (!pSession)
			{
				pSession = new CHTTPClientSession(resolvedURI.getHost(), resolvedURI.getPort());

				if (proxyUri.empty())
				{
					if (!m_proxyHost.empty())
					{
						pSession->setProxy(m_proxyHost, m_proxyPort);
						pSession->setProxyCredentials(m_proxyUsername, m_proxyPassword);
					}
				}
				else
				{
					pSession->setProxy(proxyUri.getHost(), proxyUri.getPort());
					if (!m_proxyUsername.empty())
					{
						pSession->setProxyCredentials(m_proxyUsername, m_proxyPassword);
					}
				}
			}

			std::string path = resolvedURI.getPathAndQuery();
			if (path.empty()) path = "/";
			CHTTPRequest req(CHTTPRequest::HTTP_GET, path, CHTTPMessage::HTTP_1_1);

			if (authorize)
			{
				CHTTPCredentials::extractCredentials(uri, username, password);
				CHTTPCredentials cred(username, password);
				cred.authenticate(req, res);
			}

			pSession->sendRequest(req);
			std::istream& rs = pSession->receiveResponse(res);
			bool moved = (res.getStatus() == CHTTPResponse::HTTP_MOVED_PERMANENTLY || 
				res.getStatus() == CHTTPResponse::HTTP_FOUND || 
				res.getStatus() == CHTTPResponse::HTTP_SEE_OTHER ||
				res.getStatus() == CHTTPResponse::HTTP_TEMPORARY_REDIRECT);
			if (moved)
			{
				resolvedURI.resolve(res.get("Location"));
				if (!username.empty())
				{
					resolvedURI.setUserInfo(username + ":" + password);
				}
				throw CURIRedirection(resolvedURI.toString());
			}
			else if (res.getStatus() == CHTTPResponse::HTTP_OK)
			{
				return new CHTTPResponseStream(rs, pSession);
			}
			else if (res.getStatus() == CHTTPResponse::HTTP_USEPROXY && !retry)
			{
				// The requested resource MUST be accessed through the proxy 
				// given by the Location field. The Location field gives the 
				// URI of the proxy. The recipient is expected to repeat this 
				// single request via the proxy. 305 responses MUST only be generated by origin servers.
				// only use for one single request!
				proxyUri.resolve(res.get("Location"));
				delete pSession; 
				pSession = 0;
				retry = true; // only allow useproxy once
			}
			else if (res.getStatus() == CHTTPResponse::HTTP_UNAUTHORIZED && !authorize)
			{
				authorize = true;
				retry = true;
				CNullOutputStream null;
				CStreamCopier::copyStream(rs, null);
			}
			else throw HTTPException(res.getReason(), uri.toString());
		}
		while (retry);
		throw HTTPException("Too many redirects", uri.toString());
	}
	catch (...)
	{
		delete pSession;
		throw;
	}
}

void CHTTPStreamFactory::registerFactory()
{
	CURIStreamOpener::defaultOpener().registerStreamFactory("http", new CHTTPStreamFactory);
}

void CHTTPStreamFactory::unregisterFactory()
{
	CURIStreamOpener::defaultOpener().unregisterStreamFactory("http");
}

NET_NAMESPACE_END
